import './index.scss';

import React from 'react';
import { Menu } from 'antd';
import { useLocation, useNavigate } from 'react-router';
import type { MenuProps } from "antd";
import router from '../../../router/index';
import LayoutStore from '../../../store/LayoutStore';

type MenuItem = Required<MenuProps>['items'][number];



const LayoutSider: React.FC = (props: any) => {
    const location = useLocation(); // 获取路由
    const navigate = useNavigate(); // 路由跳转
    const collapsed = LayoutStore((state) => state.collapsed); // 折叠状态

    const { routes } = router; // 获取路由配置

    const rootRoutes = routes.filter((r: any) => r.path == "/").find((r: any) => r.children)?.children || [];
    const menuItems = generateMenuItems(rootRoutes);

    // 生成layout菜单的sider侧边栏
    function generateMenuItems(routes: any[], basePath = ""): MenuItem[] {
        return routes
            .filter(route => route.meta?.title)
            .map(route => {
                const fullPath = route.path?.startsWith("/")
                    ? route.path
                    : `${basePath}/${route.path}`;

                const menuItem: MenuItem = {
                    key: fullPath,
                    label: route.meta?.title,
                    icon: <i className={`iconfont ${route.meta?.icon}`}></i>,
                    children: route.children
                        ? generateMenuItems(route.children, fullPath)
                        : undefined,
                };
                return menuItem;
            });
    };

    // 点击菜单
    const changeMenuItem = (e: any) => {
        navigate(e.key)
    }

    return (
        <div className='layout-sider'>
            <div className='layout-sider-tit'>
                <span>{collapsed ? '瑜伽馆' : '瑜伽馆后台'}</span>
            </div>
            <Menu mode="inline" theme="dark" items={menuItems} onClick={(e) => changeMenuItem(e)}></Menu>
        </div>
    );
}

export default LayoutSider;
